<template>
  <div class="home page-tab">
    <div class="header">
      <span ref="cancelBtn" v-show="this.query" class="home-back" @click="this.onCancel">
        <van-icon name="arrow-left" class="arrow"/>
      </span>
      <van-search
        ref="searchBox"
        v-model="value"
        :shape="this.query?'square':'round'"
        :background="this.query?'':'#4fc08d'"
        placeholder="请输入搜索关键词"
        :show-action="this.query"
        @focus="focus"
        left-icon
        @cancel="onClear"
      >
        <template #action>
          <div>搜索</div>
        </template>
      </van-search>
    </div>
    <van-pull-refresh
      v-show="!this.query"
      v-model="showFlag"
      success-text="刷新成功"
      @refresh="onRefresh"
    >
      <div v-show="result">
        <div class="v-shop-swipe">
          <van-swipe :autoplay="3000" class="v-shop-swip">
            <van-swipe-item v-for="(banner, index) in result.banners" :key="index">
              <img :title="banner.storeName" v-lazy="banner.image">
            </van-swipe-item>
          </van-swipe>
        </div>
        <div class="nav-menu">
          <a
            v-for="(m,index) in result.category"
            :key="index"
            @click="$router.push(m.url)"
            :data-url="m.url"
            class="nav-menu-item"
          >
            <!-- <div class="pic"><van-icon :name="m.icon" /></div> -->
            <div class="pic">
              <img v-lazy="m.pic">
            </div>
            <div class="txt" v-text="m.name"></div>
          </a>
        </div>
        <!-- 热门 -->
        <product-card title="热门榜单" subTitle="Best ~" :list="result.hotList"></product-card>
        <!-- 精品 -->
        <product-list title="精品" subTitle="Best ~" :list="result.bestList"></product-list>
        <product-list type="card" title="推荐" subTitle="Suggest ~" :list="result.firstList"></product-list>
        <product-list title="促销" subTitle="Promote ~" :list="result.promoteList"></product-list>
        <!-- </div> -->
        <more-product title="热销商品" url="/home/good/more"></more-product>
      </div>
      <div style="height:1.5rem"></div>
    </van-pull-refresh>
    <SearchMain
      v-show="query"
      :list="dataArr"
      @details="searchDetails"
      :len="len"
      :value="value"
      @vals="vals"
    />
    <div
      v-show="searchLoading"
      class="van-loading van-loading--circular van-loading--white"
      style="color: white;z-index:999"
    >
      <span class="van-loading__spinner van-loading__spinner--circular">
        <svg viewBox="25 25 50 50" class="van-loading__circular">
          <circle cx="50" cy="50" r="20" fill="none"></circle>
        </svg>
      </span>
    </div>
    <BaseFooter active="0"/>
    <router-view/>
  </div>
</template>

<script>
import SearchMain from "@/components/home/SearchMain";
import BaseFooter from "@/components/public/BaseFooter";
import ProductCard from "@/components/home/ProductCard";
import ProductList from "@/components/home/ProductList";
import MoreProduct from "@/components/home/MoreProduct";

import { vuexData, page } from "@/assets/js/mixin";
import { throttle } from "@/assets/js/util";

export default {
  name: "Home",
  mixins: [page, vuexData],
  data() {
    return {
      query: false, // 显示搜索
      len: false, // 是否含有搜索结果
      value: "",
      searchLoading: false,
      result: ""
    };
  },
  components: {
    SearchMain,
    ProductCard,
    ProductList,
    MoreProduct,
    BaseFooter
  },
  methods: {
    onClear() {
      this.value = "";
    },
    onCancel() {
      this.onClear();
      this.tran(false);
      this.query = false;
    },
    focus() {
      this.tran(true);
      this.query = true;
    },
    tran(flag) {
      let boxW = "90%",
        btnW = "10%";
      if (!flag) {
        boxW = "100%";
        btnW = "0%";
      }
      this.$refs.searchBox.style.width = boxW;
      this.$refs.searchBox.style["transitionDuration"] = ".4s";
      setTimeout(() => {
        this.$refs.cancelBtn.style.width = btnW;
        this.$refs.cancelBtn.style["transitionDuration"] = ".4s";
      }, 0);
    },
    vals(val) {
      this.value = val;
    },
    searchDetails(id) {
      console.log("id", id);
      this.$refs.input.blur();
      this.$router.push({ name: `Details`, query: { id } });
    },
    scrollToEnd() {
      if (this.dataArr.length >= 20) {
        if (this.hasMore()) {
          this.page++;
          this.search(this.value, true);
        } else {
          this.$toast("没有很多数据了~~");
        }
      }
    },
    scroll(e) {
      Math.abs(e.y) == 0
        ? (this.touch.scroll = true)
        : (this.touch.scroll = false);
      if (this.transformY > 0) {
        this.$refs.scroll.disable();
      }
    },

    touchstart(e) {
      this.isRotate = false;
      this.trans = false;
      this.touch.init = true;
      this.touch.startY = e.touches[0].pageY; //第一次点击的位置
    },
    touchmove(e) {
      if (
        !this.touch.scroll ||
        !this.touch.init ||
        e.touches[0].pageY > window.innerHeight
      )
        return;
      let pageY = e.touches[0].pageY;
      let daltaY = pageY - this.touch.startY; //滑动的位置
      this.transformY = Math.max(0, daltaY / 3.5);
      this.rotate = Math.max(0, Math.min(360, daltaY));
      if (this.transformY > 80) this.touch.isRotate = true;
      this.opac = daltaY / 320;
    },
    async touchend(e) {
      this.$refs.scroll.enable();
      if (this.transformY > 0) this.trans = true;
      this.isRotate = true;
      if (!this.touch.isRotate) {
        this.transformY = 0;
        this.isRotate = false;
        setTimeout(() => {
          this.opac = 0;
        }, 300);
      } else {
        this.touch.isRotate = false;
        if (this.transformY > 100) {
          // 请求接口刷新数据
          try {
            const { data, code } = await this.Api.initHome();
            if (code == 200) {
              this.result = data;
              this.floorName = data.floorName;
            }
            setTimeout(() => {
              this.isRotate = false;
              this.opac = 0;
              this.$toast("刷新成功");
            }, 1500);
          } catch (error) {
            this.$toast("刷新失败,网络错误");
          }
          setTimeout(() => {
            this.transformY = 0;
            this.rotate = 0;
          }, 1000);
        } else {
          this.transformY = 0;
          this.rotate = 0;
          this.isRotate = false;
        }
      }
    },
    scrollToEnd2() {
      this.$refs.scroll.refresh();
    },
    //搜索
    async search(value, flag) {
      try {
        if (this.isLocked()) return; // 必须等待上一次请求完成
        this.locked(); //开始请求之前锁住
        this.searchLoading = true;
        this.len = false;
        const { data, code } = await this.Api.searchKey(value, this.page);
        console.log("data,code", data, code);
        if (code == "200") {
          this.setTotal(data.count); // 总条数

          if (flag) {
            this.setNewData(data.list);
          } else {
            this.dataArr = data.list;
          }

          if (!this.dataArr.length) {
            this.len = true;
          }
          this.unLocked(); // 解锁
          this.searchLoading = false;
        }
      } catch (error) {
        this.unLocked(); // 解锁
        this.len = false;
        this.$toast("网络错误");
      }
    },
    onRefresh() {
      console.log("111111", 111111);
      this.initHome();
    },
    async initHome() {
      this.showFlag = true;
      const { data } = await this.Api.initHome();
      this.result = data;
      this.setTab(data.category);
      // 延迟一下效果更好
      setTimeout(() => {
        this.showFlag = false;
      }, 1000);
    }
  },
  created() {
    this.initHome();
    // 节流函数处理 防抖
    this.$watch(
      "value",
      throttle(() => {
        this.dataArr = [];
        if (this.value) {
          this.page = 1;
          this.search(this.value, false);
        }
      }, 800)
    );
  },
  watch: {
    city() {
      this.this.initHome();
    }
  }
};
</script>
<style lang="less" scoped>
@color: #f2f2f2;
@txt-color1: #333;
.header{
  background:#fff;
}
.home-back {
  float: left;
  line-height: 1.5rem;
  text-align: center;
  align-items: center;
}

.v-shop-swipe {
  height: 4.95rem;
}
.v-shop-swip.van-swipe {
  height: 100%;
  img {
    height: 100%;
    width: 100%;
  }
}
.nav-menu {
  padding-top: 0.26rem;
  display: flex;
  flex-wrap: wrap;
  .nav-menu-item {
    width: 25%;
    text-align: center;
    font-size: 0.26rem;
    .pic,
    .txt {
      width: 100%;
      font-size: 0.35rem;
      text-align: center;
    }
    .pic {
      height: 1.5rem;
      font-size: 58px;
      color: rgb(79, 192, 141);
      margin: 0 auto 12px auto;
      i {
        border-radius: 50%;
        background: gainsboro;
      }
      img {
        width: 1.5rem;
        height: 1.5rem;
      }
    }
    .txt {
      height: 25px;
      color: @txt-color1;
    }
  }
}
.adv-pic {
  width: 7.5rem;
  img {
    width: 100%;
  }
}
</style>